var express = require('express')
var app = require('express')()
var server = require('http').createServer(app)
var io = require('socket.io')(server)
const fs = require('fs')
const mysql = require('mysql')
const querstring = require('querystring')  //快速生成json字符串
const request = require('request')   // 后端发起请求
const bodyParser = require('body-parser')  // 处理前端发送的数据
const path = require('path')  //快速获取路径
const jwt = require('jsonwebtoken')

// const login = require('./fun/login')

// const token = jwt.sign()

// 使用body-parser可以接收前端的数据量比较大的数据  如果没有用这个一遍接收不了
app.use(bodyParser.json({limit: '50mb'}))   
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))
// 以上两行代码是用来接收前台发送过来的数据  可以让数据直接json话

let connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database:'jxchat'
})

connection.connect()

// socketid = {
//     'id1': 'asd',
//     'di2': 'dsa'
// }

let socketUser = {}
let user = []
let i = 0
// let arr = []
io.on('connection', function (socket) {
    let idaa = socket.client.id
    io.to(idaa).emit('ids', socket.client.id)
    console.log('a user login!')
    console.log(socketUser)
    socket.on('chat', obj => {
        console.log(obj)
        let { objuser,header, sendmsg } = obj
        console.log(socketUser[objuser])
        // console.log(sendmsg)
        io.to(socketUser[objuser]).emit('sendone', { chatobj:objuser,header:header,say:sendmsg })
    })
})

// login
app.post('/userLogin', (req, res) => { 
    let { phone, password } = req.body
    // console.log('5'+phone)
    user.push(phone)
    const sql = `select status from usermsg where phone = "${phone}"`
    connection.query(sql, (err, data) => { 
        let { status } = data[0]
        if (status === 0) {
            let promise = new Promise((resolve, reject) => {
                let sql = `select password from usermsg where phone = "${phone}"`
                connection.query(sql, (err, data, fired) => {
                    try {
                        let sqlres = data[0].password
                        if (sqlres === password) {
                            let userobj = {
                                phone: phone,
                                password: password
                            }
                            var secretOrPrivateKey = "I am a goog man!"
                            var token = jwt.sign(userobj, secretOrPrivateKey, {
                                expiresIn: 60 * 60 * 24
                            })
                            let sqlall = `select * from usermsg where phone = "${phone}"`
                            connection.query(sqlall, (err, data, fired) => {
                                let selql = `update usermsg set status = 1 where phone = "${phone}"`
                                connection.query(selql, (err, data) => { 
                                })
                                let userallmsg = JSON.stringify(data[0])
                                resolve({ msg: 'success', tokenId: token, userMsg: userallmsg })
                            })
                        } else {
                            resolve({ msg: 'error' })
                        }
                    } catch{
                        reject({ msg: 'error' })
                    }
                    
                })
            })
            promise.then(ress => {
                res.send(ress)
            })
        } else { 
            res.send({msg:'tsdl'})
        }
    })
    
})

// socketUser
app.post('/socketUser', (req, res) => {
    // console.log('I'+user)
    // console.log(i)
    // console.log(user[i])
    let { username,socketis } = req.body
    socketUser[username] = socketis
    ++i
    console.log(socketUser)
    console.log('添加用户成功')
    res.send('添加用户成功')
})

/* POST */
// register
app.post('/userregister', (req, res) => { 
    let { userName, phone, password,imgscr,imgname } = req.body
    // console.log(userName, phone, password, imgname)
    let name = imgname.split(':')[1].split(';')[0].replace('/', '.')
    // console.log(name)
    let radom = Math.ceil(Math.random()*10000)  //ceil向上取整  floor向下取整
    // console.log(radom)
    let img = Buffer.from(imgscr, 'base64')
    let header = ''
    let promise = new Promise((resolve, reject) => { 
        fs.writeFile(__dirname+`/headPortrait/${radom}${name}`, img, (err,data) => { 
            if (err) {
                reject(err)
            } else { 
                console.log('写入成功')
                header = `../../Server/headPortrait/${radom}${name}`
                // resolve(header)
                let sql = `insert into usermsg values ("${phone}","${userName}","${password}","${header}")`
                connection.query(sql, (err, data, fired) => {
                    try {
                        if (data.affectedRows === 1) {
                            resolve({msg: '写入数据库成功',code:200})
                        }
                        if (err.errno === 1062) { 
                            reject({msg:`手机号${phone}已经注册过了`,code:1062})
                        }
                    } catch{ 
                        reject({msg:'写入失败',code:1062})
                    }
                })
            }
        })
    })
    promise.then(ress => { 
        res.send(ress)
    }).catch(errs => { 
        res.send(errs)
    })

    // console.log(header)
})

// getlist
app.post('/getalluser', (req, res) => {
    let promise = new Promise((resolve, reject) => { 
        let userid = ''
        for (const key in req.body) {
            userid = key
        }
        const sql = `select username,header from usermsg where phone != "${userid}"`
        connection.query(sql, (err, data) => { 
            try {
                resolve({ msg: data, code: 200 })
            } catch{ 
                reject({msg:'获取失败',code:404})
            }
        })
    })
    promise.then(ress => { 
        res.send(ress)
    }).catch(errs => { 
        res.send(errs)
    })
    
})

// weather
app.post('/weather', (req, res) => { 
    let city = ''
    for (const key in req.body) {
        city = key
    }
    var queryData = querstring.stringify({
        'city': city,
        'key':'9d83e432ce432cb1311e2e8e303c3c5d'        
    })
    let cityWeatherUel = 'http://apis.juhe.cn/simpleWeather/query?' + queryData
    request(cityWeatherUel, (err, response, body) => { 
        try {
            // let msg = JSON.stringify(body)
            console.log(body)
            res.send(body)
        } catch{ 
            res.send('出现错误')
        }
    })
})

// getfriendmoments
app.get('/allmoments', (req, res) => { 
    let promise = new Promise((resolve, reject) => { 
        let sql = `select * from friendmonents`
        connection.query(sql, (err, data, fired) => { 
            try {
                if (data) {
                    resolve({ msg: data, code: 200 })
                }
            } catch{ 
                reject({msg:'获取失败',code:404})
            }
        })
    })
    promise.then(ress => { 
        res.send(ress)
    }).catch(errs => { 
        res.send(errs)
    })
})

// sendfriendsmoment
app.post('/sendfriendsmoment', (req, res) => { 
    let { user, phone, imgs,say,userhead } = req.body
    let imgname,imgbase64
    imgs.forEach(item => { 
        imgname = item.split(',')[0]
        imgbase64 = item.split(',')[1]
    })
    imgname = imgname.split(';')[0].split(':')[1].replace('/', '.')
    let radom = Math.ceil(Math.random()*10000)
    let promise = new Promise((resolve, reject) => { 
        let img = Buffer.from(imgbase64,'base64')
        let time = gettime()
        const getid = 'select friendmonentsid from friendmonents order by friendmonentsid desc'
        connection.query(getid, (err, data) => { 
            var itemid = parseInt(data[0].friendmonentsid)
            fs.writeFile(__dirname + `/friendmoments/${itemid+1}${imgname}`, img, (err, data) => {
                console.log()
                if (err) {
                    reject(err)
                } else {
                    console.log('照片写入成功')
                    let url = `../../Server/friendmoments/${itemid+1}${imgname}`
                    let sql = `insert into friendmonents values ("${itemid+1}","${phone}","${userhead}","${user}","${say}","${url}","${time}")`
                    connection.query(sql, (err, data, fired) => { 
                        try {
                            if (data.affectedRows === 1) {
                                resolve({ msg:'朋友圈写入成功',code:200})
                            }
                        } catch{ 
                            console.log(err)
                            reject({msg:'发布失败',code:404})
                        }
                    })
                }
            })
        })
    })
    promise.then(ress => {
        res.send(ress)
    }).catch(errs => { 
        res.send(errs)
    })
})

// getminemoments
app.post('/minemoments', (req, res) => { 
    let promise = new Promise((resolve, reject) => { 
        let data = ''
        for (const key in req.body) {
            data = key
        }
        let sql = `select * from friendmonents where userName = "${data}"`
        connection.query(sql, (err, data, fired) => { 
            try {
                if (data) {
                    resolve({ msg: data, code: 200 })
                } else { 
                    reject({msg:err,code:404})
                }
            } catch{ 
                reject({ msg: '查询失败', code: 404 })
            }
        })
    })
    promise.then(ress => { 
        res.send(ress)
    }).catch(errs => { 
        res.send(errs)
    })
})

// delonemonent
app.post('/delonemonent', (req, res) => { 
    let id = ''
    for (const key in req.body) {
        id = key
    }
    let localLink = __dirname+`/friendmoments/${id}image.jpeg`
    fs.unlink(localLink, (err) => { 
        if (err) { 
            throw err
        }
        console.log(`本地文件${localLink}已经删除`)
    })
    const sql = `delete from friendmonents where friendmonentsid = "${id}"`
    connection.query(sql, (err, data,fired) => { 
        try {
            console.log(data)
            if (data.affectedRows === 1) {
                res.send({ msg: '删除成功', code: 200 })
            } else { 
                console.log(err)
            }
        } catch{ 
            res.send({msg:'删除失败', code:404})
        }
    })
})

app.post('/outlogin', (req, res) => { 
    let phone
    for (let item in req.body) {
        phone = item
    }
    let sql = `update usermsg set status = 0 where phone = "${phone}"`
    connection.query(sql,(err, data) => {
        if (data.changedRows === 1) {
            res.send({ msg: 'ok', status: 200 })
        } else { 
            res.send({msg:'err',status:404})
        }
    })
})

// gettime
function gettime() { 
    let data = new Date()
    let year = data.getFullYear()
    let monen = data.getMonth()+1
    let day = data.getDate()
    let hour = data.getHours()
    let min = data.getMinutes()
    if (hour <= 9) { 
        hour = '0'+hour
    }
    if (min <= 9) { 
        min = '0'+min
    }
    if (monen <= 9) { 
        monen = '0'+monen
    }
    if (day <= 9) { 
        day = '0'+day
    }
    return `${year}-${monen}-${day} ${hour}:${min}`
}



// socket.io连接

// promise.then(ress => { 
//     console.log(ress)
// })




server.listen(666, () => { 
    console.log('Server is running on port 666')
})